﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Xceed.Wpf.Toolkit.PropertyGrid;

namespace WPFDemo
{
    public class Demo
    {

        public void Run()
        {
            BenchmarkRunner(typeof(SimpleTester));

            var pg = new PropertyGrid();
            pg.SelectedObject = new Person { Age = 1 };
            

            //BenchmarkRunner<SimpleTester>();
        }

        //void BenchmarkRunner<T>(int count =10000) where T : new() //泛型，必须是构造方法
        //{
        //    var obj = new T();

        //   var methods =  typeof(T).GetMethods()
        //        .Where(mi => mi.GetCustomAttribute<BenchmarkAttribute>() is not null);

        //    foreach (var method in methods)
        //    {
        //        var sw =Stopwatch.StartNew();

        //        for (int i=0;i<count;i++)
        //        {
        //            method.Invoke(obj, null);
        //        }             
        //    }
        //}


        void BenchmarkRunner(Type type, int count = 10000)
        {
            var obj = Activator.CreateInstance(type);

            var methods = type.GetMethods()
                 .Where(mi => mi.GetCustomAttribute<BenchmarkAttribute>() is not null);
            foreach (var method in methods)
            {
                var sw = Stopwatch.StartNew();

                for (int i = 0; i < count; i++)
                {
                    method.Invoke(obj, null);
                }
            }
        }


    }

    public class SimpleTester
    {
        private IEnumerable<int> testList = Enumerable.Range(1, 10).ToArray();

        [Benchmark]
        public int CalcMinByLinq()
        {
            return testList.Min();
        }

        [Benchmark]
        public int CalcMinNaive()
        {
            int min = int.MaxValue;
            foreach (var test in testList)
            {
                if (test < min)
                {
                    min = test;
                }
            }
            return min;
        }

    }

    [AttributeUsage(AttributeTargets.Method)]
    class BenchmarkAttribute:Attribute
    {

    }

}
